package com.yunxin.admin.system.infra.persistence.repository;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunxin.admin.system.domain.model.user.*;
import com.yunxin.admin.system.infra.persistence.converter.UserConverter;
import com.yunxin.admin.system.infra.persistence.entity.SysUserDO;
import com.yunxin.admin.system.domain.model.user.UserSimple;
import com.yunxin.admin.system.infra.persistence.mapper.SysUserMapper;
import com.yunxin.admin.system.infra.persistence.mapper.SysUserRoleMapper;
import com.yunxin.core.admin.domain.AdminUserMerchant;
import com.yunxin.core.admin.domain.AdminUserTeamShip;
import com.yunxin.core.admin.service.AdminUserMerchantService;
import com.yunxin.core.admin.service.AdminUserTeamShipService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * @author zero°
 * @since 2023-07-11
 */
@Repository
@RequiredArgsConstructor
public class UserRepositoryImpl extends ServiceImpl<SysUserMapper, SysUserDO> implements UserRepository, IService<SysUserDO> {

    private final UserConverter userConverter;

    private final UserRoleRepository userRoleRepository;

    private final UserMerchantRepository userMerchantRepository;

    private final SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private AdminUserTeamShipService adminUserTeamShipService;
    @Autowired
    private AdminUserMerchantService adminUserMerchantService;


    @Override
    public UserSimple getUserSimpleByUsername(String userName) {
        SysUserDO sysUserDO = this.getOne(new LambdaQueryWrapper<SysUserDO>()
                .eq(SysUserDO::getUsername, userName)
                .select(
                        SysUserDO::getId,
                        SysUserDO::getNickname,
                        SysUserDO::getAvatar
                )
        );
        return userConverter.toUserSimple(sysUserDO);
    }

    @Override
    public boolean saveUser(User user, String defaultEncryptPwd) {
        String username = user.getUsername();
        long count = this.count(new LambdaQueryWrapper<SysUserDO>().eq(SysUserDO::getUsername, username));
        Assert.isTrue(count == 0, "用户名已存在");
        String mobile = user.getMobile();
        long countPhone = this.count(new LambdaQueryWrapper<SysUserDO>().eq(SysUserDO::getMobile, mobile));
        Assert.isTrue(countPhone == 0, "手机号已存在");
        SysUserDO sysUserDO = userConverter.formUser(user);
        sysUserDO.setPassword(defaultEncryptPwd);
        sysUserDO.setExport(user.getExport());
        sysUserDO.setIsView(user.getIsView());
        sysUserDO.setWeightId(user.getWeightId());
        // 新增用户
        boolean result = this.save(sysUserDO);
        user.setId(sysUserDO.getId());
        if (result) {
            if (Objects.nonNull(user.getMerchantId()) && user.getMerchantId() > 0) {
                //userMerchantRepository.saveUserMerchant(sysUserDO.getId(), List.of(user.getMerchantId()));
                AdminUserMerchant userMerchant = new AdminUserMerchant();
                userMerchant.setUserId(user.getId());
                userMerchant.setMerchantId(user.getMerchantId());
                adminUserMerchantService.save(userMerchant);
            }
            userRoleRepository.saveUserRoles(sysUserDO.getId(), user.getRoleIds());
        }
        return result;
    }

    @Override
    public boolean updateUser(User user) {
        String username = user.getUsername();
        long count = this.count(new LambdaQueryWrapper<SysUserDO>()
                .eq(SysUserDO::getUsername, username)
                .ne(SysUserDO::getId, user.getId())
        );
        Assert.isTrue(count == 0, "用户名已存在");
        String mobile = user.getMobile();
        long countPhone = this.count(new LambdaQueryWrapper<SysUserDO>()
                .eq(SysUserDO::getMobile, mobile)
                .ne(SysUserDO::getId, user.getId()));
        Assert.isTrue(countPhone == 0, "手机号已存在");
        SysUserDO sysUserDO = userConverter.formUser(user);
        sysUserDO.setIsView(user.getIsView());
        sysUserDO.setExport(user.getExport());
        sysUserDO.setWeightId(user.getWeightId());
        // 修改用户
        boolean result = this.updateById(sysUserDO);
        if (result) {
//            if (Objects.nonNull(user.getMerchantId()) && user.getMerchantId() > 0) {
//                // 保存用户商户
//                //userMerchantRepository.saveUserMerchant(sysUserDO.getId(), List.of(user.getMerchantId()));
//                LambdaQueryWrapper<AdminUserMerchant> queryWrapper = new LambdaQueryWrapper<>();
//                queryWrapper.eq(AdminUserMerchant::getUserId, user.getId());
//                AdminUserMerchant userMerchant = adminUserMerchantService.getOne(queryWrapper);
//                if (ObjectUtils.isEmpty(userMerchant)) {
//                    userMerchant.setUserId(user.getId());
//                    userMerchant.setMerchantId(user.getMerchantId());
//                    adminUserMerchantService.save(userMerchant);
//                } else {
//                    LambdaUpdateWrapper<AdminUserMerchant> updateWrapper = new LambdaUpdateWrapper<>();
//                    updateWrapper.eq(AdminUserMerchant::getUserId, user.getId())
//                            .set(AdminUserMerchant::getMerchantId, user.getMerchantId());
//                    adminUserMerchantService.update(updateWrapper);
//                }
//            }
            userRoleRepository.saveUserRoles(sysUserDO.getId(), user.getRoleIds());
        }
        return result;
    }

    @Override
    public boolean removeByIdList(Collection<Long> ids) {
        return this.removeByIds(ids);
    }

    @Override
    public boolean updateStatus(Long id, Integer status) {
        return this.update(new LambdaUpdateWrapper<SysUserDO>()
                .eq(SysUserDO::getId, id)
                .set(!ObjectUtils.isEmpty(status), SysUserDO::getStatus, status));
    }

    @Override
    public boolean updatePassword(Long id, String password) {
        return this.update(new LambdaUpdateWrapper<SysUserDO>()
                .eq(SysUserDO::getId, id)
                .set(SysUserDO::getPassword, password)
        );
    }


    /**
     * 根据用户id修改用户角色
     *
     * @param userId
     * @param roleId
     */
    @Override
    public void updateUserRole(Long userId, Integer roleId) {
        sysUserRoleMapper.updateUserRole(userId, roleId);
    }
}
